import fs from "fs";
import test from "tape";
import path from "path";
import { fileURLToPath } from "url";
import { loadJsonFileSync } from "load-json-file";
import { writeJsonFileSync } from "write-json-file";
import { truncate } from "@turf/truncate";
import { featureCollection, point } from "@turf/helpers";
import { getCoord } from "@turf/invariant";
import { featureEach } from "@turf/meta";
import { shortestPath } from "./index.js";

const __dirname = path.dirname(fileURLToPath(import.meta.url));

const directories = {
  in: path.join(__dirname, "test", "in") + path.sep,
  out: path.join(__dirname, "test", "out") + path.sep,
};

const fixtures = fs.readdirSync(directories.in).map((filename) => {
  return {
    filename,
    name: path.parse(filename).name,
    geojson: loadJsonFileSync(directories.in + filename),
  };
});

test("turf-shortest-path", (t) => {
  for (const { filename, name, geojson } of fixtures) {
    // First two features from Collection are Start & End Points
    const start = geojson.features.shift();
    const end = geojson.features.shift();
    // Any remaining features from Collection are obstacles
    const obstacles = geojson;
    const options = geojson.properties;
    options.obstacles = obstacles;

    const path = truncate(shortestPath(start, end, options));
    path.properties["stroke"] = "#F00";
    path.properties["stroke-width"] = 5;

    const results = featureCollection([]);
    if (obstacles) {
      featureEach(obstacles, (obstacle) => {
        results.features.push(obstacle);
      });
    }
    results.features.push(point(getCoord(start), start.properties));
    results.features.push(point(getCoord(end), end.properties));
    results.features.push(path);

    if (process.env.REGEN)
      writeJsonFileSync(directories.out + filename, results);
    t.deepEqual(results, loadJsonFileSync(directories.out + filename), name);
  }
  t.end();
});

test("turf-shortest-path -- with polygon feature as obstacle", (t) => {
  const filename = "simple.json";
  const geojson = loadJsonFileSync(directories.in + filename);

  const start = geojson.features.shift();
  const end = geojson.features.shift();
  const obstacle = geojson.features.shift();

  const path = truncate(
    shortestPath(start, end, {
      ...geojson.properties,
      obstacles: obstacle,
    })
  );
  path.properties["stroke"] = "#F00";
  path.properties["stroke-width"] = 5;

  const results = featureCollection([]);
  results.features.push(obstacle);
  results.features.push(point(getCoord(start), start.properties));
  results.features.push(point(getCoord(end), end.properties));
  results.features.push(path);

  t.deepEqual(results, loadJsonFileSync(directories.out + filename), "simple");
  t.end();
});
